package ch02.test01;

import java.io.*;

/**
 * 用户线程
 *
 * @author lwj
 * @date 2025-03-07
 * @vesion 1.0.0
 */
public class UserThread extends Thread{
    /**
     * 输入流地址
     */
    private String filePath;
    /**
     * 输出流地址
     */
    private String descFilePath;
    /**
     * 文件总大小
     */
    private volatile  long fileSize = 0;
    /**
     * 拷贝时的大小
     */
    private volatile long copySize = 0;

    // 构造方法
    public UserThread(String filePath, String descFilePath) {
        this.filePath = filePath;
        this.descFilePath = descFilePath;

        File file = new File(filePath);
        // 获取文件总大小
        fileSize = file.length();
    }

    @Override
    public void run() {
        // 创建输入流对象
        FileInputStream fileInputStream = null;
        // 创建输出流对象
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            fileOutputStream = new FileOutputStream(descFilePath);
            // 字节数组
            byte[] buf = new byte[7];
            // 读取的长度
            int len;
            while((len = fileInputStream.read(buf)) != -1){
                // 边读边写
                fileOutputStream.write(buf,0,len);
                copySize += len;// 累加拷贝的字节数
                // System.out.println(copySize);
            }
            System.out.println("文件拷贝成功");
        } catch (IOException e) {
            System.out.println("文件拷贝失败");
            throw new RuntimeException(e);
        } finally {
            try{
                // 判断是否创建了对象
                if(fileInputStream != null){
                    fileInputStream.close();
                }
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // 获取拷贝进度百分比（0-100）
    public int getCopySize() {
        if (fileSize == 0) return 0;
        return (int) (copySize * 100 / fileSize);
    }
}
